package com.oitsm.mo.entity;

import java.util.Date;

import org.apache.log4j.Logger;
import org.quartz.CronExpression;

import com.oitsm.utils.TimeUtil;

/**
 * 采集时间计划 - 计划有两种类型,一种是延迟N秒后采集,一种是使用CRON表达式
 * @author Arab Runner
 * Jul 24, 2011 3:05:23 PM
 */
public class Schedule {
	/**
	 * 时间模式 - 延迟N毫秒
	 */
	public final static int TYPE_DELAY = 0;
	/**
	 * 时间模式 - CRON表达式
	 */
	public final static int TYPE_CRON = 1; 
	
	public static Logger logger = Logger.getLogger(Schedule.class.getName());
	
	private long miId;
	/**
	 * 当时间表达式不正确时,此项有可能为空
	 */
	private Long nextTime;
	private long lastTime;
	/**
	 * 类型
	 */
	private int type = 0;
	/**
	 * 时间计划字符串
	 */
	private String scheduleString;
	
	/**
	 * CRON表达式
	 */
	private CronExpression cron;
	
	// 默认3分钟
	private Long delay;
	
	/**
	 * 设置 时间
	 */
	public void setSchedule(String scheduleStr){
		this.scheduleString = scheduleStr;
		String[] strs = scheduleStr.split(":");
		if("delay".equals(strs[0])){
			type = TYPE_DELAY;
			try{
				delay = Long.parseLong(strs[1]);
			}catch(Exception e){
				delay = null;
				logger.error(e.getMessage());
			}
		}else{
			type = TYPE_CRON;
			try{
				cron = new CronExpression(strs[1]);
			}catch(Exception e){
				cron = null;
				logger.error(e.getMessage());
			}
		}
	}
	
	public String getScheduleString(){
		return scheduleString;
	}
	
	public CronExpression getCron(){
		return cron;
	}
	
	public Long getDelay(){
		return delay;
	}
	
	/**
	 * 初始化 时间计划
	 */
	public void init(String scheduleStr) {
		setSchedule(scheduleStr);
		next(-1l);
	}
	
	/**
	 * 计算下次时间
	 */
	public void next(long lastTime){
		if(lastTime!=-1){
			this.lastTime = lastTime;
		}
		
		if(type == TYPE_CRON && this.cron != null){
			Date d = new Date();
			d.setTime(this.lastTime);
			nextTime = this.cron.getNextValidTimeAfter(d).getTime();
		}else if(type == TYPE_DELAY && this.delay != null){
			this.nextTime = this.lastTime + delay;
		}else{
			nextTime = null;
		}
	}
	
	public static void main(String[] args)throws Exception{
		String c = "*/5 * * * * ?";
		CronExpression cc = new CronExpression(c);
		
		System.out.println(System.currentTimeMillis());
		
		Date d = new Date();
		for(int i=0;i<30;i++){
			d = cc.getNextValidTimeAfter(d);
			System.out.println(TimeUtil.format(d));
		}
		
	}
	
	public Schedule(){}

	public long getMiId() {
		return miId;
	}

	public void setMiId(long miId) {
		this.miId = miId;
	}

	public Long getNextTime() {
		return nextTime;
	}

	public long getLastTime() {
		return lastTime;
	}

	public void setLastTime(long lastTime) {
		this.lastTime = lastTime;
	}
}
